/**
 * 严肃声明：
 * 开源版本请务必保留此注释头信息，若删除我方将保留所有法律责任追究！
 * 本软件已申请软件著作权，受国家版权局知识产权以及国家计算机软件著作权保护！
 * 可正常分享和学习源码，不得用于违法犯罪活动，违者必究！
 * Copyright (c) 2019-2021 十三 all rights reserved.
 * 版权所有，侵权必究！
 */
package ltd.newbee.mall.service;

import cn.hutool.core.convert.Convert;
import ltd.newbee.mall.common.Constants;
import ltd.newbee.mall.common.RedisClient;
import ltd.newbee.mall.entity.AdminUserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class NewBeeAdminUserTokenService {
    private static int expireTime = 2 * 24 * 60 * 60;
    @Autowired
    private RedisClient redisClient;

    public void deleteByPrimaryKey(Long userId){
        Object token=redisClient.get(Constants.USER_ID_TO_TOKEN+userId);
        if(token!=null) {
            redisClient.del(Constants.TOKEN_TO_USER_ID + token);
            redisClient.del(Constants.USER_ID_TO_TOKEN + userId);
        }
    }

    public void insertSelective(AdminUserToken record){
        Long userId = record.getAdminUserId();
        String token = record.getToken();

        redisClient.setex(Constants.USER_ID_TO_TOKEN+ userId, expireTime, token);
        redisClient.setex(Constants.TOKEN_TO_USER_ID+ token, expireTime, Convert.toStr(userId));
    }


    public AdminUserToken selectByPrimaryKey(Long userId)
    {
        AdminUserToken adminUserToken=null;
        Object token=redisClient.get(Constants.USER_ID_TO_TOKEN+userId);
        if(token!=null)
        {
            adminUserToken=new AdminUserToken();
            adminUserToken.setAdminUserId(userId);
            adminUserToken.setToken(token.toString());

            //续时间
            expire(userId,token.toString());

        }
        return adminUserToken;
    }

    private void expire(Long userId, String token)
    {
        redisClient.expire(Constants.USER_ID_TO_TOKEN+ userId, expireTime);
        redisClient.expire(Constants.TOKEN_TO_USER_ID+ token, expireTime);
    }

    public AdminUserToken selectByToken(String token) {
        AdminUserToken adminUserToken=null;
        Object userIdObj=redisClient.get(Constants.TOKEN_TO_USER_ID+ token);
        if(userIdObj!=null){
            adminUserToken=new AdminUserToken();
            Long userId = Convert.toLong(userIdObj);
            adminUserToken.setAdminUserId(userId);
            adminUserToken.setToken(token);
            expire(userId, token);
        }
        return adminUserToken;
    }
}